#!/usr/bin/env bash

#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#

set -e

INTEROP_DIR=target/quic-interop-runner

# Setup the s2n-quic docker image
if [[ "$*" == *'s2n-quic'* ]]; then
  sudo docker build . --file quic/s2n-quic-qns/etc/Dockerfile.build --tag aws/s2n-quic-qns --build-arg tls=s2n-tls
fi

if [[ "$*" == *'s2n-quic-rustls'* ]]; then
  sudo docker build . --file quic/s2n-quic-qns/etc/Dockerfile.build --tag aws/s2n-quic-qns-rustls --build-arg tls=rustls
fi

if [ ! -d $INTEROP_DIR ]; then
  git clone https://github.com/marten-seemann/quic-interop-runner $INTEROP_DIR
  # make sure to keep this up to date with the interop workflow
  cd $INTEROP_DIR
  git checkout bdb2c815b8cfd70de4c2efb1bd278b1e87018ff8
  git apply --3way ../../.github/interop/runner.patch
  cd ../../
fi

if [ ! -d $INTEROP_DIR/.venv ]; then
  cd $INTEROP_DIR
  python3 -m venv .venv
  source .venv/bin/activate
  pip3 install --upgrade pip
  pip3 install wheel
  cd ../../
fi

function ensure_executable() {
  if ! command -v $1 &> /dev/null; then
    echo "$1 needs to be installed"
    exit
  fi
}

ensure_executable "docker-compose"
ensure_executable "tshark"

case "$(uname -s)" in
   Linux)
     sudo modprobe ip6table_filter
     ;;
   *)
     # TODO possibly add other things for Darwin
     ;;
esac

cd $INTEROP_DIR
source .venv/bin/activate
pip install --upgrade -r requirements.txt

case "$@" in
   pull)
     python3 pull.py
     exit 0
     ;;
   *)
     # continue
     ;;
esac

python3 run.py --debug "$@"
